<script setup lang="ts">
import type { LoginParams } from '@/types/user';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { ref } from 'vue';
import { loginAPI } from '@/apis/user'
import { useUserStore } from '@/stores/userStote';
import { useRouter } from 'vue-router'
const router = useRouter()
const userStore = useUserStore()
// 登录信息
const userInfo = ref<LoginParams>({
  mobile: '17639555005',
  code: '246810'
})

const rules = ref<FormRules<LoginParams>>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur' }
  ]
})

const formRef = ref<FormInstance>()
const agree = ref<boolean>(false)

// 点击登录按钮
const onSubmit = () => {
  formRef.value?.validate(async(valid) => {
    if (valid) {
      // alert('校验成功');
      // 发起登录请求
      const res = await loginAPI(userInfo.value)
      console.log('res',res)
      // 保存token到store中
      userStore.setToken(res.data.token)
      // 登录成功，跳转到首页
      router.push("/")
      ElMessage.success('登录成功')
    } else {
      alert('校验失败');
    }
  })
}

</script>

<template>
  <div class="container">
    <el-card>
      <img class="logo" src="../../assets/logo.png" alt="" />
      <!-- 表单 -->
      <el-form ref="formRef" :model="userInfo" :rules="rules">
        <el-form-item prop="mobile">
          <el-input v-model="userInfo.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item prop="code">
          <el-input v-model="userInfo.code" placeholder="请输入验证码"></el-input>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="agree">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button :disabled="!agree" type="primary" @click="onSubmit">登 录</el-button>
        </el-form-item>
      </el-form>
      {{ userInfo }}
      {{ agree }}
    </el-card>
  </div>
</template>

<style scoped>
.container {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background: url('../../assets/login.png');

    .el-card {
      width: 440px;
      height: 380px;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      box-shadow: 0 0 50px rgba(0,0,0,0.1);

      .logo {
        width: 200px;
        display: block;
        margin: 0 auto 20px;
      }
    }
  }
  .el-form {
  padding: 0 20px;
  .el-button {
    width: 100%;
    height: 40px;
  }
  .el-form-item .el-input{
    height:40px ;
    margin-top: 10px
  }
}
</style>